<template>
  <div class="app-container" style="padding: 20px;">
    <div class="fifter-channel">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" style="display: flex;">
        <div>
          <el-form-item label="上架渠道" style="margin-right: 40px;">
            <el-input v-model="formInline.channelName" placeholder="请输入渠道名称" size="small" clearable @keydown.native="keydown($event)"></el-input>
            <!-- <el-select v-model="formInline.channelName" placeholder="请选择上架渠道">
              <el-option v-for="(item,index) in channelList" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
            </el-select> -->
          </el-form-item>
          <el-form-item label="城市">
            <el-input v-model="formInline.deptName" placeholder="请输入城市名称" size="small" clearable @keydown.native="keydown($event)"></el-input>
            <!-- <el-select v-model="formInline.deptName	" placeholder="请选择城市">
              <el-option v-for="(item,index) in cityList" :key="index" :label="item.deptName" :value="item.deptName"></el-option>
            </el-select> -->
          </el-form-item>
        </div>
        <div>
          <el-form-item>
            <el-button type="primary" plain @click="onSubmit" icon="el-icon-search"  size="small">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" plain icon="el-icon-plus" @click="onAddCityChannel" size="small">新建</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" -->
    <div class="main-channel">
      <el-table ref="multipleTable"  :data="tableData"
        border style="width: 100%;">
        <el-table-column prop="deptName" label="城市" width="180">
        </el-table-column>
        <el-table-column prop="channelNames" label="上架渠道">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="190">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="warning" size="mini">编辑</el-button>
            <el-button type="danger" @click.native.prevent="deleteRow(scope.$index, tableData)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <el-pagination background :current-page.sync="currentPage" layout="prev, pager, next, sizes, total, jumper"
      :page-sizes="[5, 10, 15, 20]" :page-size.sync="pagesize" :total="total" @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination> -->
    <pagination v-show="total>0" :total="total" :page.sync="formInline.page" :limit.sync="formInline.size" @pagination="getList" />
    <el-dialog :visible.sync="cityChannelFlag" center :append-to-body="true" :lock-scroll="false" width="60%" z-index="2007">
      <div style="width: 100%;height: 450px;">
        <el-scrollbar class="page-component__scroll" style="height: 400px;">
          <el-col>
            <div class="order-message" style="height: 35px;">
              <el-col style="display: flex;padding-left: 5px;font-size: 20px;color: #409EFF;align-items: center;">
                <span style="display: block;width: 5px;height: 22px;background: #409EFF;margin-right: 10px;"></span>
                新增团购城市渠道
              </el-col>
            </div>
            <div style="height: 300px;margin-left: 25px;">
              <div v-if="cityNoEditFlag">
                <el-form :model="addCityChannelForm" :rules="addCityChannelrules" ref="addCityChannelForm" label-width="80px"
                  class="demo-ruleForm">
                  <el-form-item label="城市">
                    <!-- <el-input
                      v-model.number="addCityChannelForm.city"
                      placeholder="请输入城市名称"
                      style="width: 300px;"
                    ></el-input> -->
                    <span>{{ addCityChannelForm.city }}</span>
                  </el-form-item>
                  <el-form-item label="上架渠道">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                      <el-checkbox v-for="city in channelList" :label="city" :key="city.dictValue" border>{{city.dictValue}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item style="display: flex;justify-content: flex-end;margin-right: 10%;">
                    <el-button @click="addCityChannelResetForm('addCityChannelForm')">取消</el-button>
                    <el-button type="primary" @click="addCityChannelSubmitForm('addCityChannelForm')">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div v-if="cityEditFlag">
                <el-form :model="addCityChannelEditForm" :rules="addCityChannelrules" ref="addCityChannelEditForm"
                  label-width="80px" class="demo-ruleForm">
                  <el-form-item v-if="cityEditFlag" label="城市">
                    <!-- <el-input v-model="formInline.cityName" placeholder="请输入城市名称" size="small"></el-input> -->
                    <el-select v-model="addCityChannelEditForm.deptId" placeholder="请选择城市">
                      <el-option v-for="(item,index) in cityList" :key="index" :label="item.deptName" :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="上架渠道">
                    <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                      <el-checkbox v-for="city in channelList" :label="city" :key="city.dictValue" border>{{city.dictValue}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item style="display: flex;justify-content: flex-end;margin-right: 10%;">
                    <el-button @click="addCityChannelEditResetForm('addCityChannelEditForm')">取消</el-button>
                    <el-button type="primary" @click="addCityChannelEditSubmitForm('addCityChannelEditForm')">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-scrollbar>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getBydeptId, //根据城市ID查询记录
    getChannelList, // 渠道
    queryDeptChannel, // 查询列表
    saveOrUpdate, // 新增/修改城市渠道记录
    deleteChannel, // 删除城市渠道记录
  } from "@/api/commodityfiles";
  import {
    deptdepts
  } from "@/api/shop";
  import Pagination from "@/components/Pagination"; //分页
  export default {
    components: {
      Pagination
    },
    data() {
      return {
        total: 0,
        pagesize: 10,
        currentPage: 1,
        listLoading: true,
        // 列表部分------------------------------------------------------------
        listQuery: {
          // page: 2,
          size: 30
        },
        formInline: {
          //查询条件
          deptId: '',
          name: "", //商品名称
          goodsState: "", //商品状态
          categoryId: "", //商品类型
          channelName: '',
          deptName: '',
          page: 1,
          size: 10
        },
        formInlineCopy: {
          channelName: 1,
          deptName: 2,
        },
        channelList: '', // 渠道列表
        cityList: '', // 城市列表deptsCity
        getBydeptId: { // 根据城市id查询记录
          deptId: 9000,
        },
        cityChannelFlag: false, // 新建城市渠道标记开关
        multipleSelection: [],
        tableData: [],
        addCityChannelForm: {
          city: '',
          deptId: 2,
          channelIds: ''
        },
        addCityChannelEditForm: {
          city: '',
          deptId: '',
          channelIds: ''
        },
        addCityChannelrules: {},
        checkAll: false,
        checkedCities: [],
        isIndeterminate: true,
        deleteChannelList: { // 删除城市渠道记录
          deptId: 0
        },
        cityNoEditFlag: false, // 城市不可编辑Flag
        cityEditFlag: false, // 城市可编辑Flag
      }
    },
    watch: {
      'cityChannelFlag'() {
        if(this.cityChannelFlag) {
          window.removeEventListener("keydown",this.keyupEnter);
        } else {
          window.addEventListener("keydown",this.keyupEnter);
        }
      },
    },
    mounted() {
      this.getList()
      deptdepts("").then(res => {
        this.cityList = res.data.data
        // console.log(res.data.data, this.$store.state.user)
      })
      getChannelList({'type': 2}).then(res => {
        this.channelList = res.data.data
        // console.log(res.data.data, this.$store)
      })
      window.addEventListener("keydown",this.keyupEnter);
    },
    methods: {
      getList() {
        //列表数据
        this.listLoading = true;
        queryDeptChannel(this.formInline).then(response => {
          this.tableData = response.data.data.rows;
          this.total = response.data.data.total;
          // console.log(this.tableData,'this.tableData')
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      },
      onSubmit() {
        // console.log(this.formInline)
        this.formInline.page = 1;
        this.cityList.forEach((item, index) => {
          if (this.formInline.deptName == this.cityList[index].deptName) {
            this.formInline.deptId = this.cityList[index].id
          }
        })
        this.formInlineCopy.channelName = this.formInline.channelName
        this.formInlineCopy.deptName = this.formInline.deptName
        queryDeptChannel(this.formInline).then(res => {
          this.tableData = res.data.data.rows
          this.total = res.data.data.total;
          // console.log(res.data.data)
        })
      },
      // 列表编辑操作
      handleClick(row) {
        // console.log(row,'row')
        this.cityChannelFlag = true;
        this.cityNoEditFlag = true;
        this.cityEditFlag = false;
        this.getBydeptId.deptId = row.deptId
        this.addCityChannelForm.deptId = row.deptId
        this.addCityChannelForm.id = row.id
        getBydeptId(this.getBydeptId).then(res => {
          // console.log(res.data.data,'this.cityList')
          let string = res.data.data.channelIds
          let objdata = string.split(",")
          let Numarr = []
          objdata.forEach(item => {
            this.channelList.forEach(channel => {
              if (item == channel.dictKey) {
                Numarr.push(channel)
              }
            })
          })
          this.checkedCities = Numarr
          this.cityList.forEach((item, index) => {
            if (res.data.data.deptId == this.cityList[index].id) {
              this.addCityChannelForm.city = this.cityList[index].deptName // 编辑请求城市
            }
          })
          this.getList()
        })
      },
      // 全选,反选
      handleCheckAllChange(val) {
        const cityOptions = this.channelList;
        this.checkedCities = val ? cityOptions : [];
        this.isIndeterminate = false;
        // console.log('this.checkedCities01',this.checkedCities)
      },
      handleCheckedCitiesChange(value) {
        this.delUndefined(value)
        // console.log(value,'value','this.checkedCities02',this.checkedCities)
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.channelList.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.channelList.length;
      },
      // 去处数组里面的undefined
      delUndefined(arr) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] === undefined) {
            arr.splice(i, 1)
            i = i - 1 // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位
          }
        }
      },
      // 新增城市渠道
      onAddCityChannel() {
        this.checkedCities = []
        this.cityChannelFlag = true
        this.cityNoEditFlag = false;
        this.cityEditFlag = true;
      },
      // 删除操作
      deleteRow(index, rows) {
        this.deleteChannelList.deptId = rows[index].deptId
        deleteChannel({deptId:rows[index].deptId}).then(res => {
          if (res.data.code == 200) {
            this.$notify({
              title: '删除渠道成功',
              message: '已成功删除渠道',
              type: 'success'
            })
            setTimeout(() => {
              rows.splice(index, 1)
            }, 1 * 1000)
          }
          this.getList()
        })
      },
      // 新增城市&渠道
      addCityChannelSubmitForm(formName) { // 新增城市&渠道保存按钮
        // console.log(this.checkedCities)
        const Numarr = []
        this.checkedCities.forEach(item => {
          Numarr.push(item.dictKey)
        })
        this.addCityChannelForm.channelIds = Numarr.join(',')
        // console.log('this.addCityChannelForm',this.addCityChannelForm)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            saveOrUpdate(this.addCityChannelForm).then(res => {
              // console.log(res)
              if (res.data.code == 200) {
                this.$notify({
                  title: '编辑渠道成功',
                  message: '已成功编辑渠道',
                  type: 'success'
                })
                this.$refs[formName].resetFields();
                setTimeout(() => {
                  this.cityChannelFlag = false;
                }, 1.5 * 1000)
                this.getList()
              }
            })
          } else {
            return false;
          }
        });
      },
      addCityChannelResetForm(formName) { // 新增城市&渠道保存按钮
        this.$refs[formName].resetFields();
        this.cityChannelFlag = false;
      },
      // 新增城市&渠道
      addCityChannelEditSubmitForm(formName) { // 新增城市&渠道保存按钮
        this.addCityChannelEditForm.id = ''
        const Numarr = []
        this.checkedCities.forEach(item => {
          Numarr.push(item.dictKey)
        })
        this.addCityChannelEditForm.channelIds = Numarr.join(',')
        // console.log('this.checkedCities',this.checkedCities)
        this.$refs[formName].validate((valid) => {
          if (valid) {
            saveOrUpdate(this.addCityChannelEditForm).then(res => {
              if (res.data.code == 200) {
                this.$notify({
                  title: '新建渠道成功',
                  message: '新建渠道成功',
                  type: 'success'
                })
                this.$refs[formName].resetFields();
                setTimeout(() => {
                  this.cityChannelFlag = false;
                }, 1.5 * 1000)
                this.getList()
              }
            })
          } else {
            return false;
          }
        });
      },
      addCityChannelEditResetForm(formName) {
        this.$refs[formName].resetFields();
        this.cityChannelFlag = false;
      },
      handleCurrentChange() {

      },
      handleSizeChange() {

      },
      // 禁止输入空格
      keydown(e) {
        if(e.keyCode == 32) {
          e.returnValue = false;
        }
      },
      // 回车事件
      keyupEnter(){
        if(window.event.keyCode == 13 ){
          this.onSubmit();// 查询事件
        }
      },
    },
    destroyed() {
      window.removeEventListener("keydown",this.keyupEnter);
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown",this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown",this.keyupEnter);
    }
  };
</script>

<style lang="scss">
  .app-container {
    .fifter-channel {
      margin-bottom: 20px!important;
    }
    .main-channel{
      margin-bottom: 20px!important;
    }
    .demo-form-inline {
      display: flex;
      justify-content: space-between;
    }

    .el-table td,
    .el-table th.is-leaf {
      text-align: center;
    }

    .el-scrollbar {
      padding-bottom: 15px;
    }

  }
</style>
